import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:osg/controllers/custom_widget.dart';
import 'package:osg/controllers/http.dart';
import 'package:osg/controllers/my_method.dart';

RxList times = [].obs;
RxList qxx = [].obs;

List qxu = [];
double maxValue = 0;
RxInt type = 1.obs;

class TransactionRecord extends StatefulWidget {
  TransactionRecord({super.key});

  @override
  State<TransactionRecord> createState() => _SettingPageState();
}

class _SettingPageState extends State<TransactionRecord> {
  String? id = Get.parameters['id'];
  String? title = Get.parameters['title'];

  RxMap info = {}.obs;
  RxList clist = [].obs;

  getInfo() {
    Get.find<HTTPS>().getData('/market/resalesLog', {
      "product_id": '$id',
      "per_page": '499',
      "type": '$type',
    }).then((res) {
      if (res != null) {
        times.value = [];
        qxx.value = [];
        info.value = res;
        for (var i = 0; i < res['qx'].length; i++) {
          times.add(res['qx'][i]['time']);
          qxx.add(res['qx'][i]['count'].toDouble());
        }
        maxValue = qxx.reduce((a, b) => a > b ? a : b);
        clist.value = res['list'];
      }

    });
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          backgroundColor: Color(0xffffffff),
          title: Text('$title',style: TextStyle(fontSize: 16),),
          centerTitle: true),
      body: ListView(
        padding: EdgeInsets.symmetric(horizontal: 15),
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('今日成交总额',
                      style: TextStyle(fontSize: 12, color: Color(0XFF999999))),
                  Row(
                    children: [
                      Obx(
                        () => Text('${info['today_money']}',
                            style: TextStyle(
                                fontSize: 30,
                                color: Color(0XFF0F172B),
                                fontWeight: FontWeight.bold)),
                      ),
                      Text('元',
                          style: TextStyle(
                              fontSize: 14, color: Color(0XFF0F172B))),
                    ],
                  )
                ],
              ),
              SizedBox(),
              Column(
                children: [
                  SizedBox(
                    height: 15,
                  ),
                  Text('今日成交量',
                      style: TextStyle(fontSize: 12, color: Color(0XFF999999))),
                  Obx(
                    () => Text('${info['today_count']}',
                        style: TextStyle(
                            fontSize: 21,
                            color: Color(0XFF0F172B),
                            fontWeight: FontWeight.bold)),
                  ),
                ],
              ),
              SizedBox()
            ],
          ),
          SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Column(
                children: [
                  Text('今日最高价',
                      style: TextStyle(fontSize: 11, color: Color(0XFF999999))),
                  Obx(
                    () => Text('￥${info['today_max']}',
                        style:
                            TextStyle(fontSize: 13, color: Color(0XFFEF0000))),
                  ),
                ],
              ),
              SizedBox(
                width: 110,
              ),
              Column(
                children: [
                  Text('今日最低价',
                      style: TextStyle(fontSize: 11, color: Color(0XFF999999))),
                  Obx(
                    () => Text('￥${info['today_min']}',
                        style:
                            TextStyle(fontSize: 13, color: Color(0XFF00B602))),
                  ),
                ],
              ),
            ],
          ),
          SizedBox(
            height: 20,
          ),
          Obx(() => Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: () {
                      type.value = 1;
                      getInfo();
                    },
                    child: Container(
                      width: 105,
                      decoration: BoxDecoration(
                          color: type.value == 1
                              ? Color(0XFF0F172B)
                              : Color(0XFFF8F9FD),
                          borderRadius: BorderRadius.circular(5)),
                      height: 37,
                      alignment: Alignment.center,
                      child: Text('5分钟',
                          style: TextStyle(
                              fontSize: 14,
                              color: type.value == 1
                                  ? Color(0XFfffffff)
                                  : Color(0XFF0F172B))),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      type.value = 2;
                      getInfo();
                    },
                    child: Container(
                      width: 105,
                      decoration: BoxDecoration(
                          color: type.value == 2
                              ? Color(0XFF0F172B)
                              : Color(0XFFF8F9FD),
                          borderRadius: BorderRadius.circular(5)),
                      height: 37,
                      alignment: Alignment.center,
                      child: Text('1小时',
                          style: TextStyle(
                            fontSize: 14,
                            color: type.value == 2
                                ? Color(0XFfffffff)
                                : Color(0XFF0F172B),
                          )),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      type.value = 3;
                      getInfo();
                    },
                    child: Container(
                      width: 105,
                      decoration: BoxDecoration(
                          color: type.value == 3
                              ? Color(0XFF0F172B)
                              : Color(0XFFF8F9FD),
                          borderRadius: BorderRadius.circular(5)),
                      height: 37,
                      alignment: Alignment.center,
                      child: Text('1天',
                          style: TextStyle(
                            fontSize: 14,
                            color: type.value == 3
                                ? Color(0XFfffffff)
                                : Color(0XFF0F172B),
                          )),
                    ),
                  ),
                ],
              )),
          Container(
            margin: EdgeInsets.only(top: 20,left:25),
            height: 250,
            child: Obx(() => qxx.isNotEmpty
                ? TimeLineChart(spots: [
                    for (var item in times.asMap().entries)
                       FlSpot(item.key.toDouble(), qxx[item.key].toDouble()),
                  ])
                : SizedBox()),
          ),
          Obx(() => Column(
                children: [
                  if (clist.isEmpty) 
                  isdata(),

                  for (var item in clist)
                    Container(
                        margin: EdgeInsets.only(top: 15),
                        padding:
                            EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                        decoration: BoxDecoration(
                            color: Color(0XFFF8F9FD),
                            borderRadius: BorderRadius.circular(10)),
                        child: Row(
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                    '# ${Get.find<MyMethod>().hao('${item['nftId']}')}',
                                    style: TextStyle(
                                        fontSize: 18,
                                        color: Color(0XFF0F172B))),
                                Text('${item['complete_at']}',
                                    style: TextStyle(
                                        fontSize: 12,
                                        color: Color(0XFF999999))),
                              ],
                            ),
                            Expanded(child: SizedBox()),
                            Text('￥',
                                style: TextStyle(
                                    fontSize: 12, color: Color(0XFF0F172B))),
                            Text('${item['money_price']}',
                                style: TextStyle(
                                    fontSize: 18, color: Color(0XFF0F172B))),
                          ],
                        ))
                ],
              ))
        ],
      ),
    );
  }
}

// class LineChartExample extends StatelessWidget {
//   final List<double> data = [10, 12, 8, 15, 20, 18, 25]; // 示例数据

//   @override
//   Widget build(BuildContext context) {
//     return LineChart(
//       LineChartData(
//         gridData: FlGridData(show: true),
//         titlesData: FlTitlesData(show: true),
//         borderData: FlBorderData(show: true),
//         lineBarsData: [
//           LineChartBarData(
//             spots: data.asMap().entries.map((e) {
//               return FlSpot(e.key.toDouble(), e.value);
//             }).toList(),
//             isCurved: true,
//             color: Color(0XFF542AFF),
//             // colors: [Colors.blue],
//             dotData: FlDotData(show: false),
//             belowBarData: BarAreaData(show: true, color: Color.fromRGBO(15, 23, 43, 0.3)),
//           ),
//         ],
//       ),
//     );
//   }
// }

class TimeLineChart extends StatelessWidget {
  final List<FlSpot> spots;

  TimeLineChart({required this.spots});

  @override
  Widget build(BuildContext context) {
    return LineChart(
      LineChartData(
        minY: 0,
        maxY: maxValue < 1 ? 180 : maxValue,
        lineBarsData: [
          LineChartBarData(
             preventCurveOverShooting: true,
            spots: spots,
            isCurved: true,
            dotData: FlDotData(show: true),
          ),
        ],
        titlesData: FlTitlesData(
          bottomTitles: AxisTitles(
            sideTitles: SideTitles(
              reservedSize: 40,
              showTitles: true,
              interval: 1,
              getTitlesWidget: (value, meta) {
                // 5分钟间隔的6个时间点
                return Container(
                    margin: EdgeInsets.only(top: 15),
                    child: Obx(
                      () => times.isNotEmpty
                          ?Text(times[value.toInt()])
                          : SizedBox(),
                    ));
              },
            ),
          ),
           topTitles: AxisTitles(
             sideTitles: SideTitles(
               showTitles: false,
             )
           ),
           rightTitles: AxisTitles(
             sideTitles: SideTitles(
              reservedSize: 40,
                showTitles: true,
          interval: _calculateSmartInterval(), 
               
             )
           ),
          leftTitles: AxisTitles(
            sideTitles: SideTitles(
              showTitles: false,
              reservedSize: 40,
              interval: 30, // y轴间隔
              getTitlesWidget: (value, meta) {
                return Text(value.toInt().toString());
              },
            ),
          ),
        ),
        gridData: FlGridData(show: true),
      ),
    );
  }
}

double _calculateSmartInterval( ) {
  if (maxValue <= 10) return 2;
  if (maxValue <= 100) return 20;
  return (maxValue / 5).ceilToDouble();
}